import {PlusOutlined} from '@ant-design/icons';
import {Button, message, Drawer, FormInstance, Popconfirm, Image, Tag, Divider} from 'antd';
import React, {useState, useRef} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import type {ProColumns, ActionType} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  ModalForm,
  ProFormText,
  ProFormDateRangePicker,
  ProFormCascader,
  ProFormUploadButton,
  ProFormTextArea,
  ProFormList,
  ProFormGroup,
  ProFormDependency,
} from '@ant-design/pro-form';
import ProDescriptions, {ProDescriptionsItemProps} from '@ant-design/pro-descriptions';
import {
  removeData,
  dataList,
  addData,
  updateData,
  loadData,
  loadCheckData,
  saveCheckData,
} from './service';
import type {AssessmentBody, AssessmentListItem, AssessmentListPagination} from './data';

import moment, {Moment} from 'moment';
import 'moment/locale/zh-cn';
import {loadOrgSelect, sensitiveTest} from '@/pages/Enterprise/Org/service';
import CheckModule from '@/components/CheckModule';

/**
 * 添加节点
 *
 * @param fields
 * @param mode
 */

const handleAdd = async (fields: AssessmentBody, mode: boolean) => {
  const hide = message.loading(mode ? '正在保存' : '正在添加');

  try {
    mode ? await updateData({...fields}) : await addData({...fields});
    hide();
    message.success(mode ? '保存成功' : '添加成功');
    return true;
  } catch (error) {
    // hide();
    // message.error(mode ? '保存失败请重试' : '添加失败请重试');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: AssessmentListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeData(selectedRows.map((row) => row.assessmentId));
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const submitCheckFile = (values: AssessmentBody, fileName: string, dataName: string) => {
  if (values[fileName]) {
    let file = values[fileName][0];
    values[dataName] = file?.response?.data?.url || file.url;
  }
};
const AssessmentPage: React.FC = (props, context) => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [checkModalVisible, handleCheckModalVisible] = useState<boolean>(false);
  const [checkEdit, setCheckEdit] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [orgSelectAll, setOrgSelectAll] = useState<[][number]>([][0]);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [currentRow, setCurrentRow] = useState<AssessmentListItem>();
  const columns: ProColumns<AssessmentListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      valueType: 'indexBorder',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionRef?.current?.pageInfo?.current || 1) - 1) *
              (actionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInDescriptions: true,
      render: (_, record) => {
        if (record.status == 0) {
          return [
            <a
              key="view"
              onClick={() => {
                formRef.current?.resetFields();
                setCurrentRow(record);
                setShowDetail(true);
              }}
            >
              查看
            </a>,
            <a
              key="edit"
              onClick={() => {
                formRef.current?.resetFields();
                console.log(record);
                setCurrentRow(record);
                setEditMode(true);
                handleModalVisible(true);
              }}
            >
              编辑
            </a>,
            <a
              key="check"
              onClick={() => {
                formRef.current?.resetFields();
                console.log(record);
                setCurrentRow(record);
                handleCheckModalVisible(true);
              }}
            >
              考核
            </a>,
            <Popconfirm
              key="delete"
              okButtonProps={{danger: true}}
              title={`删除后无法恢复,确认删除?`}
              onConfirm={async () => {
                setCurrentRow(record);
                await handleRemove([record]);
                actionRef.current?.reloadAndRest?.();
              }}
              okText="删除"
              cancelText="取消"
            >
              <a href="@/pages/Defense/System/Assessment/index#"> 删除 </a>
            </Popconfirm>,
          ];
        } else
          return [
            <a
              key="view"
              onClick={() => {
                formRef.current?.resetFields();
                setCurrentRow(record);
                setShowDetail(true);
              }}
            >
              查看
            </a>,
            <a
              key="check"
              onClick={() => {
                formRef.current?.resetFields();
                console.log(record);
                setCurrentRow(record);
                handleCheckModalVisible(true);
                setCheckEdit(true);
              }}
            >
              考核结果
            </a>,
          ];
      },
    },
    {
      title: '考核名称',
      dataIndex: 'assessmentName',
    },
    {
      title: '考核部门',
      hideInSearch: true,
      dataIndex: 'orgNameList',
      // ellipsis: true,
      render: (_, record) => (
        <>
          {record?.orgNameList?.map(function (name: string[], index: number) {
            return <Tag key={'orgNameList-' + index + record.assessmentId}>{name.join(' - ')}</Tag>;
          })}
        </>
      ),
    },
    {
      title: '是否考试',
      dataIndex: 'status',
      align: 'center',
      valueEnum: {
        1: {
          text: '已考核',
          status: 'Success',
        },
        0: {
          text: '未考核',
          status: 'Error',
        },
      },
    },
    {
      search: false,
      title: '考核时间',
      align: 'center',
      dataIndex: 'assessmentTime',
    },
    {
      search: false,
      hideInTable: true,
      title: '考核范围',
      dataIndex: 'assessmentScope',
    },
    {
      search: false,
      hideInTable: true,
      title: '考核依据',
      dataIndex: 'accordingFile',
      render: (_, record) =>
        record.accordingFile ? (
          <a href={record.accordingFile} target={'_blank'}>
            查看
          </a>
        ) : (
          <>-</>
        ),
    },
    {
      search: false,
      hideInTable: true,
      title: '完成时间',
      align: 'center',
      dataIndex: 'completeTime',
    },
    {
      title: '创建时间',
      sorter: true,
      align: 'center',
      defaultSortOrder: 'descend',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      search: false,
    },
    // {
    //   title: '更新时间',
    //   sorter: true,
    //   dataIndex: 'updateTime',
    //   valueType: 'dateTime',
    //   search: false,
    // },
  ];

  const [editMode, setEditMode] = useState<boolean>(false);
  const [previewData, setPreviewData] = useState({
    visible: false,
    image: '',
    title: '',
  });

  const uploadProps = {
    headers: {
      Authorization: `Bearer ${localStorage.getItem('token')}`,
    },
    multiple: false,
    // onPreview: async (file: UploadFile) => {
    //   window.open(file?.response?.data?.path || file.url, '_blank')
    // },
    name: 'file',
    max: 1,
  };

  const disabledDate = (current: Moment) => {
    return current && current < moment().subtract(1, 'days').endOf('day');
  };

  const selectAllOrg = () => {
    formRef.current?.setFieldsValue({orgList: orgSelectAll});
  };
  const requestOrg = async () => {
    return loadOrgSelect({status: '0'}).then(({data}) => {
      let map = data.map((item) => {
        return [item.id];
      });
      // @ts-ignore
      setOrgSelectAll(map);
      console.log(orgSelectAll, '2222');
      sensitiveTest();
      return data;
    });
  };
  const displayRender = (labels: string[], selectedOptions: any[]) =>
    labels.map((label, i) => {
      const option = selectedOptions[i];
      if (i === labels.length - 1) {
        return <span key={option?.value}>{label}</span>;
      }
      return <span key={option?.value}>{label} / </span>;
    });

  const dropdownRender = (menus: React.ReactNode) => (
    <div>
      {menus}
      <Divider key={'ext-divider'} style={{margin: 0}}/>
      <Button key={'choose-all'} type="text" block icon={<PlusOutlined/>} onClick={selectAllOrg}>
        全部选择
      </Button>
    </div>
  );
  // @ts-ignore
  return (
    <CheckModule code={'SC'}>
      <PageContainer waterMarkProps={{content: ''}}>
        <ProTable<AssessmentListItem, AssessmentListPagination>
          headerTitle={'考核列表'}
          actionRef={actionRef}
          rowKey="assessmentId"
          search={{
            labelWidth: 120,
          }}
          scroll={{x: 1500}}
          options={false}
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                setEditMode(false);
                handleModalVisible(true);
              }}
            >
              <PlusOutlined/> 新建
            </Button>,
          ]}
          request={dataList}
          columns={columns}
        />
        <ModalForm<AssessmentBody>
          title={currentRow?.assessmentId || 0 > 0 ? '编辑考核' : '新建考核'}
          formRef={formRef}
          layout={'horizontal'}
          labelCol={{span: 4}}
          wrapperCol={{span: 18}}
          visible={createModalVisible}
          onValuesChange={(changedValues) => {
            if (changedValues && changedValues.hasOwnProperty('dateRange')) {
              formRef.current?.setFieldsValue({
                startTime: changedValues.dateRange[0] + '',
              });
              formRef.current?.setFieldsValue({endTime: changedValues.dateRange[1] + ''});
              formRef.current?.setFieldsValue({
                assessmentTime: changedValues.dateRange[0] + '至' + changedValues.dateRange[1],
              });
            }
            console.log(changedValues);
          }}
          onVisibleChange={(visible) => {
            if (!visible) {
              setCurrentRow(undefined);
            }
            handleModalVisible(visible);
          }}
          modalProps={{destroyOnClose: true, maskClosable: false}}
          onFinish={async (value) => {
            console.log(value);
            submitCheckFile(value, 'accordingFileData', 'accordingFile');
            const success = await handleAdd(value, editMode);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                // @ts-ignore
                actionRef.current?.reloadAndRest();
              }
            }
          }}
          request={async (param) => {
            if (param.assessmentId > 0) {
              const {data} = await loadData(param as AssessmentBody);
              data.dateRange = [data.startTime ?? '', data.endTime ?? ''];
              if (data.startTime) data.startTime = data.startTime + ' 00:00:00';
              if (data.endTime) data.endTime = data.endTime + ' 00:00:00';

              if (data.accordingFile)
                data.accordingFileData = [
                  {
                    url: data.accordingFile,
                    name: '考核依据',
                    status: 'done',
                  },
                ];
              return data;
            } else {
              return new Promise<AssessmentBody>((resolve) => {
                resolve({
                  assessmentId: 0,
                });
              });
            }
          }}
          params={{...currentRow}}
        >
          <ProFormText hidden name="assessmentId"/>
          <ProFormText hidden name="assessmentTime"/>
          <ProFormText hidden name="startTime"/>
          <ProFormText hidden name="endTime"/>
          <ProFormText hidden name="sort" initialValue={0}/>
          <ProFormText rules={[{required: true}]} label={'考核名称'} name="assessmentName"/>
          <ProFormCascader
            name="orgList"
            label="考核部门"
            extra={<a onClick={selectAllOrg}>全选部门</a>}
            request={requestOrg}
            fieldProps={{
              multiple: true,
              // @ts-ignore
              displayRender: displayRender,
              dropdownRender: dropdownRender,
              fieldNames: {
                label: 'label',
                value: 'id',
                children: 'children',
              },
            }}
            rules={[{required: true}]}
          />

          <ProFormDateRangePicker
            rules={[{required: true}]}
            name="dateRange"
            label="考核时间"
            fieldProps={{disabledDate}}
          />
          <ProFormTextArea rules={[{required: true}]} label={'考核范围'} name="assessmentScope"/>
          <ProFormUploadButton
            name="accordingFileData"
            label="考核依据"
            max={1}
            // @ts-ignore
            fieldProps={{...uploadProps}}
            action="/v2/enterprise/upload/assessment-according"
          />
        </ModalForm>

        <ModalForm
          title="安全考核"
          formRef={formRef}
          // labelCol={{span: 4}}
          // wrapperCol={{span: 18}}
          visible={checkModalVisible}
          onVisibleChange={(visible) => {
            if (!visible) {
              setCurrentRow(undefined);
            }
            handleCheckModalVisible(visible);
          }}
          modalProps={{destroyOnClose: true, maskClosable: false}}
          onFinish={async (value) => {
            console.log(value);
            if (!checkEdit) {
              const success = await saveCheckData(value);
              if (success) {
                actionRef.current?.reloadAndRest?.();
              }
            }
            handleCheckModalVisible(false);
          }}
          request={async (param) => {
            console.log(param);
            const {data} = await loadCheckData(param as AssessmentBody);
            return {assessmentId: param.assessmentId, data};
          }}
          params={{...currentRow}}
        >
          <ProFormText hidden name="assessmentId"/>
          <ProFormList
            name="data"
            actionRender={() => {
              return [];
            }}
            creatorButtonProps={false}
            itemRender={({listDom, action}, {record}) => {
              return (
                <div style={{marginBlockEnd: 15}}>
                  {' '}
                  {listDom} <Divider></Divider>
                </div>
              );
            }}
            // itemRender={({listDom, action}, {record}) => {
            //   return (
            //     <ProCard
            //       bordered
            //       extra={action}
            //       title={record?.orgLinealName.join()}
            //       style={{marginBlockEnd: 15}}
            //       bodyStyle={{padding: 0, paddingLeft: 20, paddingRight: 20, paddingTop: 20}}>
            //       {listDom}
            //     </ProCard>
            //   );
            // }}
          >
            <ProFormGroup>
              <ProFormText name="assessmentName" label="考核部门" disabled/>
              <ProFormText
                name="assessmentResult"
                label="部门考核结果"
                disabled={checkEdit}
                width={'xs'}
                rules={[{required: true}]}
              />
              <ProFormText
                name="evaluationResult"
                label="部门评估结果"
                disabled={checkEdit}
                width={'xs'}
                rules={[{required: true}]}
              />
              <ProFormText
                name="rewards"
                label="部门奖惩记录"
                width={'xs'}
                disabled={checkEdit}
                rules={[{required: true}]}
              />
            </ProFormGroup>

            <ProFormDependency name={['employeeList']}>
              {({employeeList}) => {
                if (employeeList && employeeList.length > 0) {
                  return (
                    <ProFormList
                      name="employeeList"
                      creatorButtonProps={false}
                      actionRender={() => {
                        return [];
                      }}

                      // itemRender={({listDom, action}, {record}) => {
                      //   return (
                      //     <div style={{marginBlockEnd: 15}}>     {listDom} <Divider></Divider></div>
                      //   );
                      // }}
                      // itemRender={({listDom, action}, {record}) => {
                      //   return (
                      //     <ProCard
                      //       bordered
                      //       extra={action}
                      //       title={record?.orgLinealName.join()}
                      //       style={{marginBlockEnd: 15}}
                      //       bodyStyle={{padding: 0, paddingLeft: 20, paddingRight: 20, paddingTop: 20}}>
                      //       {listDom}
                      //     </ProCard>
                      //   );
                      // }}
                    >
                      <ProFormGroup key="group">
                        <ProFormText hidden name="assessmentId"/>
                        <ProFormText hidden name="employeeId"/>
                        <ProFormText name="assessmentName" label="员工姓名" disabled width={'xs'}/>
                        <ProFormText name="assessmentPost" label="岗位" disabled width={'xs'}/>
                        <ProFormText
                          name="assessmentResult"
                          label="考核结果"
                          disabled={checkEdit}
                          width={'xs'}
                          rules={[{required: true}]}
                        />
                        <ProFormText
                          name="evaluationResult"
                          label="评估结果"
                          disabled={checkEdit}
                          width={'xs'}
                          rules={[{required: true}]}
                        />
                        <ProFormText
                          name="rewards"
                          label="奖惩记录"
                          width={'xs'}
                          disabled={checkEdit}
                          rules={[{required: true}]}
                        />
                      </ProFormGroup>
                    </ProFormList>
                  );
                } else {
                  return <></>;
                }
              }}
            </ProFormDependency>
          </ProFormList>
        </ModalForm>

        <Image
          width={200}
          style={{display: 'none'}}
          src={previewData.image}
          preview={{
            visible: previewData.visible,
            src: previewData.image,
            onVisibleChange: (value) => {
              setPreviewData({image: previewData.image, title: '', visible: value});
            },
          }}
        />
        <Drawer
          width={800}
          visible={showDetail}
          onClose={() => {
            setCurrentRow(undefined);
            setShowDetail(false);
          }}
          closable={false}
        >
          {currentRow?.assessmentId && (
            <ProDescriptions<AssessmentBody>
              column={1}
              bordered={true}
              title={'考核详情'}
              // @ts-ignore
              request={loadData}
              // layout={'vertical'}
              params={currentRow}
              columns={columns as ProDescriptionsItemProps<AssessmentBody>[]}
            />
          )}
        </Drawer>
      </PageContainer>
    </CheckModule>
  );
};

export default AssessmentPage;
